import DrawerFooter from '@/components/DrawerFooter';
import { Button, Form, Input } from '@alifd/next';
import { t } from '@lingui/macro';
import React, { useState } from 'react';

const FormItem = Form.Item;

function ChargeForm({ data: origin, onSubmit, onCancel }) {
  const [data, setData] = useState(origin);

  /**
   * 保存数据
   * @param {*} value
   */
  const handleSetData = (value) => {
    setData({
      ...data,
      ...value,
    });
  };

  // 自定义校验器，确保输入值为数字
  const numberValidator = (rule, value, callback) => {
    if (!value) {
      callback(); // 空值，不进行校验
    } else if (!/^-?\d+(\.\d+)?$/.test(value)) {
      callback('请输入有效的数字');
    } else {
      callback(); // 校验通过
    }
  };

  const nonPositiveValidator = (rule, value, callback) => {
    if (value === undefined || value === '') {
      callback(); // 如果值为空，让`required`属性处理这个错误
      return;
    }
    const numberValue = Number(value);
    if (isNaN(numberValue) || numberValue > 0) {
      callback('请输入一个负数');
    } else {
      callback(); // 验证通过，没有错误
    }
  };

  return (
    <Form
      labelAlign="top"
      fullWidth
      value={data}
      onChange={handleSetData}
      onSubmit={onSubmit}
      useLabelForErrorMessage
    >
      <FormItem
        label={t`开始价格`}
        name="startPrice"
        required
        requiredMessage={t`开始价格不能为空`}
      >
        <Input placeholder={t`请输入内容`} />
      </FormItem>
      <FormItem
        label={t`结束价格`}
        name="endPrice"
        required
        requiredMessage={t`结束价格不能为空`}
      >
        <Input placeholder={t`请输入内容`} />
      </FormItem>
      <FormItem
        label={t`发单积分`}
        name="issueOrderPoint"
        required
        validator={numberValidator}
      >
        <Input
          placeholder={t`请输入内容`}
        />
      </FormItem>
      <FormItem
        label={t`接单积分`}
        name="takeOrderPoint"
        required
        validator={nonPositiveValidator}
        requiredMessage={t`接单积分不能为空`}
      >
        <Input
          placeholder={t`请输入内容`}
        />
      </FormItem>
      <FormItem
        label={t`备注`}
        name="remarks"
        // required
        requiredMessage={t`备注不能为空`}
      >
        <Input.TextArea placeholder={t`请输入内容`} />
      </FormItem>
      <DrawerFooter>
        <FormItem>
          <Form.Submit validate type="primary" onClick={onSubmit}>{t`保存`}</Form.Submit>
          <Button style={{ marginLeft: 8 }} onClick={onCancel}>{t`取消`}</Button>
        </FormItem>
      </DrawerFooter>
    </Form>
  );
}

export default ChargeForm;
